package com.ruoyi.manager.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.CityTypeEnum;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.manager.domain.City;
import com.ruoyi.manager.domain.SoldierArrangeInfo;
import com.ruoyi.manager.mapper.CityMapper;
import com.ruoyi.manager.mapper.SoldierArrangeInfoMapper;
import com.ruoyi.manager.service.ICityService;
import com.ruoyi.manager.service.ISoldierArrangeInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 省市县级联
 *
 * @author Allen
 * @date 2021-08-30
 */
@Service
public class CityServiceImpl extends ServiceImpl<CityMapper, City> implements ICityService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<City> cityTreeList() {
        BoundValueOperations<String, String> ops = redisTemplate.boundValueOps(Constants.CITY_TREE);
        String cityJson = ops.get();
        if (StringUtils.isNotEmpty(cityJson)){
            List<City> cityList = (List<City>) JSON.parseObject(cityJson,new TypeReference<List<City>>(){});
            return cityList;
        }
        // 所有数据
        List<City> cityList = baseMapper.selectList(new QueryWrapper<City>().lambda().lt(City::getType,CityTypeEnum.TOWN.getType()));
        // 组成树型
        List<City> cityTree = cityList.stream()
                .filter(item -> Objects.equals(item.getType(), CityTypeEnum.PROVINCE.getType()))
                .map(item -> {
                    item.setCityChildren(getChildrenList(item, cityList));
                    return item;
                }).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(cityTree)) {
            ops.set(JSON.toJSONString(cityTree), 30, TimeUnit.DAYS);
        }
        return cityTree;
    }

    /**
     * 递归查找所有的子菜单
     *
     * @param city
     * @param cityList
     *
     * @return
     */
    private List<City> getChildrenList(City city, List<City> cityList) {
        if (CollectionUtil.isEmpty(cityList)) {
            return null;
        }
        return cityList.stream()
                .filter(item -> Objects.equals(item.getPid(), city.getId()))
                .map(item -> {
                    item.setCityChildren(getChildrenList(item, cityList));
                    return item;
                }).collect(Collectors.toList());
    }
}
